package com.irdstudio.apicenter.gateway.util.push;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jpush.api.common.DeviceType;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.irdstudio.apicenter.gateway.web.MaccsException;

/**
 * 消息推送工具类
 * 
 * <p>该实现目前基于【个推】  http://www.getui.com/
 * <p>针对IOS和安卓采用两种最常用的模板进行，如果有其他模板需求可参考
 * http://docs.igetui.com/pages/viewpage.action?pageId=589866
 * 
 * @author ZhangHao
 * @since 1.0
 * @date 2015-08-20
 */
public class PushUtils {

	
	/**
	 * 
	 * 消息推送公共发放
	 * 
	 * @param pushCfg 推送配置信息
	 * @param deviceType 设备类型
	 * @param title 推送标题
	 * @param alertMsg 推送显示正文
	 * @param params  推送参数信息（透传，不要于展示，可用于客户端逻辑处理）
	 * @param deviceids 设备标识（用于推送的设备唯一性标识）
	 * @param iosBadge 角标（只用于IOS）
	 * @return
	 * @throws MaccsException
	 */
	public static IPushResult pushMessage(PushCfg pushCfg, String deviceType,
			String title, String alertMsg, String params,
			List<String> deviceids, Integer iosBadge) throws MaccsException {

		logger.info("pushMessage ：" + pushCfg.toString());
		IPushResult ret = null;
		if (deviceids == null || deviceids.isEmpty()) {
			logger.info("deviceids is empty.");
			return null;
		}
		try {
			String url = pushCfg.getUrl();
			String appKey = pushCfg.getAppKey();
			String masterSecret = pushCfg.getMasterSecret();
			String appId = pushCfg.getPushAppId();

			IGtPush push = new IGtPush(url, appKey, masterSecret);
			System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
			
			if (DeviceType.IOS.value().equalsIgnoreCase(deviceType)) {
				ret = pushMessageToIOS(push, appId, appKey, title, alertMsg,
						params, deviceids, iosBadge);
			} else if (DeviceType.Android.value().equalsIgnoreCase(deviceType)) {
				ret = pushMessageToAndroid(push, appId, appKey, title,
						alertMsg, params, deviceids);
			} else
				throw new MaccsException("deviceType not found.");

			logger.info("ret ：" + ret.getResponse());
		} catch (Exception e) {
			logger.error("pushMessage error", e);
			e.printStackTrace();
			throw new MaccsException(e);
		}
		return ret;
	}

	
	/**
	 * 
	 * IOS 推送模板实现
	 * 
	 * @param push
	 * @param appId
	 * @param appKey
	 * @param title
	 * @param alertMsg
	 * @param params
	 * @param deviceids
	 * @param badge
	 * @return
	 * @throws MaccsException
	 */
	private static IPushResult pushMessageToIOS(IGtPush push, String appId,
			String appKey, String title, String alertMsg, String params,
			List<String> deviceids, Integer badge) throws MaccsException {

		String taskId = null;
		IPushResult ret = null;
		try {
			TransmissionTemplate template = new TransmissionTemplate();
			template.setAppId(appId);
			template.setAppkey(appKey);
			template.setTransmissionContent(params);
			template.setTransmissionType(1);
			APNPayload apnpayload = new APNPayload();
			// 应用icon上显示的数字
			apnpayload.setBadge(badge == null ? -1 : badge.intValue());
			// 推送直接带有透传数据
			apnpayload.setContentAvailable(1);
			// 通知铃声文件名
			apnpayload.setSound("default");
			// 在客户端通知栏触发特定的action和button显示
			apnpayload.setCategory("");
			
			APNPayload.DictionaryAlertMsg dm = new APNPayload.DictionaryAlertMsg();
			// 通知文本消息字符串
			dm.setBody(alertMsg);
			// 通知标题
			dm.setTitle(title);
			apnpayload.setAlertMsg(dm);

			template.setAPNInfo(apnpayload);
			ListMessage message = new ListMessage();
			message.setData(template);

			taskId = push.getAPNContentId(appId, message);
			logger.info("taskId ：" + taskId);
			ret = push.pushAPNMessageToList(appId, taskId, deviceids);

		} catch (Exception e) {
			logger.error("pushMessageToIOS error", e);
			e.printStackTrace();
			throw new MaccsException(e);
		} finally {

		}
		return ret;
	}

	
	/**
	 * Android 推送模板实现
	 * 
	 * @param push
	 * @param appId
	 * @param appKey
	 * @param title
	 * @param alertMsg
	 * @param params
	 * @param deviceids
	 * @return
	 * @throws MaccsException
	 */
	private static IPushResult pushMessageToAndroid(IGtPush push, String appId,
			String appKey, String title, String alertMsg, String params,
			List<String> deviceids) throws MaccsException {
		String taskId = null;
		IPushResult ret = null;
		try {

			NotificationTemplate template = new NotificationTemplate();
			// 设置APPID与APPKEY
			template.setAppId(appId);
			template.setAppkey(appKey);
			// 设置通知栏标题与内容
			template.setTitle(title);
			template.setText(alertMsg);
			// 设置通知是否响铃，震动，或者可清除
			template.setIsRing(true);
			template.setIsVibrate(true);
			template.setIsClearable(true);
			// 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
			template.setTransmissionType(1);
			template.setTransmissionContent(params);

			ListMessage message = new ListMessage();
			message.setData(template);
			List<Target> targetList = new ArrayList<Target>(deviceids.size());
			Target target = null;
			for (String deviceid : deviceids) {
				target = new Target();
				target.setAppId(appId);
				target.setClientId(deviceid);
				targetList.add(target);
			}
			taskId = push.getContentId(message);
			logger.info("taskId ：" + taskId);
			ret = push.pushMessageToList(taskId, targetList);

		} catch (Exception e) {
			logger.error("pushMessageToAndroid error", e);
			e.printStackTrace();
			throw new MaccsException(e);
		} finally {

		}
		return ret;
	}

	private final static Logger logger = LoggerFactory
			.getLogger(PushUtils.class);

	public static void main(String[] args) throws JsonParseException,
			JsonMappingException, IOException {
		PushCfg pushCfg = new PushCfg();
		// String deviceType = DeviceType.IOS.value();
		String deviceType = DeviceType.Android.value();
		String alertMsg = "这是一个透传信息.";
		Map map = new HashMap();
		map.put("content", "111111111");
		map.put("title", "title");
		ObjectMapper JSON = new ObjectMapper();

		String params = JSON.writeValueAsString(map);
		List<String> deviceids = new ArrayList<String>();
		deviceids.add("1a9dfd70b6b1d1db44f5ae1614685ca4");
		// deviceids.add("C7F269232507BA14EAC4251FA8BFB440E139AB2A2447CD3508602F4DF9334111");
		deviceids.add("1d0f28589e57b90c3e34a09c68308e81");

		try {
			// PushUtils.pushMessage(pushCfg, deviceType,"移动审批", alertMsg,
			// params,
			// deviceids);
			PushUtils.pushMessage(pushCfg, deviceType, "审批事项", alertMsg, params, deviceids, null);

		} catch (MaccsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
